<?php

namespace app\api\service;

use app\common\model\Order;
use app\common\model\OrderItem;
use app\common\model\Packaged;
use app\common\model\Packaged as PackagedModel;

class PackagedService extends BaseService
{

    public function getPackagedList(array $paginate)
    {

        $where = [
            'status' => Packaged::STATUS_ON,
        ];

        $packaged = PackagedModel::with([
            'user_dressup_package'
        ])
            ->where($where)
            ->paginate($paginate);

        $data = $packaged->items();
        $count = $packaged->total();

        foreach ($data as &$item) {
            $item['is_buy'] = $item['user_dressup_package'] ? 'Y' : 'N';
            unset($item['user_dressup_package']);
        }

        return ['list' => $data, 'count' => $count];
    }

    /**
     * 套餐详情
     * @param $id
     * @return array|bool|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPackagedDetail($id)
    {
        if (empty($id)) return false;
        $packaged = PackagedModel::with([
            'dressup',
            'user_dressup_package'
        ])->where('id', $id)->find();
        if (empty($packaged)) {
            $this->setMsg('找不到相关的套餐信息！');
            return false;
        }
        $packaged['is_buy'] = $packaged['user_dressup_package'] ? 'Y' : 'N';
        unset($packaged['user_dressup_package']);
        return $packaged;
    }



    public function submitOrder($param, $userId)
    {
        // 获取关联的装扮
        $packaged = PackagedModel::with('dressup')->where('id', 'in', $param['id'])->find();
        if (empty($packaged)) {
            $this->setMsg('没有找到相关的套餐信息！');
            return false;
        }


        $dressupPackaged['dressup_ids'] = [];
        foreach ($packaged['dressup'] as $v) {
            $dressupPackaged['dressup_ids'][] =  $v['id'];
        }


        $price = $packaged['price'];
        $discountAmount = 0;
        $qty = 1;
        $amount = bcmul($price, $qty);
        $remark = '';
        $content = json_encode($dressupPackaged);

        $order = new OrderService();
        $orderRes = $order->submit(Order::TYPE_DRESSUP, $userId, $amount, $discountAmount);
        if (empty($orderRes)) {
            $this->setMsg($order->getMsg());
            return false;
        }

        $orderItem = new OrderItemService();
        $resItem = $orderItem->submit($orderRes->id, $param['id'], OrderItem::DATA_TYPE_PACKAGED,$packaged['name'], $qty, $price, $discountAmount, $content, $remark);
        if (!$resItem) {
            $this->setMsg($orderItem->getMsg());
            return false;
        }
        $orderRes['order_item'] = $resItem;

        return $orderRes;
    }
}
